package cn.ltgodm.moj.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.ltgodm.moj.common.ErrorCode;
import cn.ltgodm.moj.exception.BusinessException;
import cn.ltgodm.moj.judge.codesandbox.CodeSandbox;
import cn.ltgodm.moj.judge.codesandbox.model.ExecuteCodeRequest;
import cn.ltgodm.moj.judge.codesandbox.model.ExecuteCodeResponse;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * 远程代码沙箱
 */
@Service
@ConfigurationProperties(prefix = "codesandbox")
@Data
public class RemoteCodeSandbox implements CodeSandbox {

    private String host;
    private String port;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url = StrUtil.format("http://{}:{}/sandbox/execute",host,port);
        String requestParam = JSONUtil.toJsonStr(executeCodeRequest);
        String body = HttpUtil.createPost(url)
                .body(requestParam)
                .execute().body();
        if (StrUtil.isBlank(body)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR.getCode(),"调用沙箱服务失败:"+body);
        }
        return JSONUtil.toBean(body, ExecuteCodeResponse.class);
    }
}
